﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 22/06/2011
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class DocumentCategoryController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /DocumentCategory/
        public ActionResult Index(int? page)
        {
            try
            {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("documentCategory.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("documentCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("documentCategory.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("documentCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("documentCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var categories = eDataContext.DocumentCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new DocumentCategoryViewModels
                    {
                        Categories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DocumentCategory/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Video))
                {
                    DocumentCategory docCat = eDataContext.DocumentCategories.Where(c => c.ID == id).SingleOrDefault();

                    List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                                                    .Where(c => c.ID != docCat.ID)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, docCat.ParentID);

                    return View(new DocumentCategoryInputModels
                    {
                        ListParentCategories = categories,
                        Category = docCat,
                        ParentID = docCat.ParentID
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DocumentCategory/Create
        public ActionResult Create()
        {
            try
            {
                    //List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                    //                                .Select(c => new TreeNodeItem()
                    //                                {
                    //                                    Value = c.ID,
                    //                                    Text = c.Name,
                    //                                    ParentID = c.ParentID
                    //                                }).ToList();
                    //TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    return View(new DocumentCategoryInputModels
                    {
                        //ListParentCategories = categories
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /DocumentCategory/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                    // TODO: Add insert logic here
                    DocumentCategory docCat = new DocumentCategory();
                    UpdateModel(docCat);
                    docCat.AddBy = UserManager.GetUserId();
                    eDataContext.DocumentCategories.InsertOnSubmit(docCat);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DocumentCategory/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    DocumentCategory docCat = eDataContext.DocumentCategories.Where(c => c.ID == id).SingleOrDefault();

                    //List<TreeNodeItem> listTree = eDataContext.DocumentCategories
                    //                                .Where(c=>c.ID != docCat.ID)
                    //                                .Select(c => new TreeNodeItem()
                    //                                {
                    //                                    Value = c.ID,
                    //                                    Text = c.Name,
                    //                                    ParentID = c.ParentID
                    //                                }).ToList();
                    //TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, docCat.ParentID);

                    return View(new DocumentCategoryInputModels
                    {
                        //ListParentCategories = categories,
                        Category = docCat,
                        ParentID = docCat.ParentID
                    });
                
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /DocumentCategory/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                    DocumentCategory docCat = eDataContext.DocumentCategories.Where(c => c.ID == id).SingleOrDefault();
                    UpdateModel(docCat);
                    docCat.ModifyBy = UserManager.GetUserId();

                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }


        //
        // GET: /Article/Delete/5
        public ActionResult Delete(short id)
        {
            try
            {
                    int nChildren = eDataContext.DocumentCategories.Where(i => i.ParentID.HasValue && i.ParentID.Value == id).Count();
                    if (nChildren > 0)
                        throw new Exception("Chuyên mục bạn xoá là chuyên mục cha nên bạn không thể xoá được. Hãy xoá chuyên mục con trước.");

                    int nItems = eDataContext.FormDocuments.Where(f => f.CatID.HasValue && f.CatID.Value == id).Count();
                    if (nItems > 0)
                        throw new Exception("Chuyên mục bạn xoá có chứa tài liệu. Hãy xoá hết tài liệu trước khi xoá chuyên mục này.");

                    DocumentCategory docCat = eDataContext.DocumentCategories.SingleOrDefault(e => e.ID == id);

                    return View(docCat);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        [Authorize()]
        public ActionResult Delete(short id, FormCollection collection)
        {
            try
            {
                    DocumentCategory docCat = eDataContext.DocumentCategories.SingleOrDefault(e => e.ID == id);
                    if (docCat != null)
                    {
                        eDataContext.DocumentCategories.DeleteOnSubmit(docCat);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
